import java.io.IOException;
import java.net.*;
public class TCPListener implements Runnable {
	private boolean _stop;
	private int _port;
	private int _ServerTimeOut;
	private int _tcpTimeOut;
	private int _msgMSS;
	private int _picMSS;
	private PictureManager _pictureManager = null;
	private long _maxIdleTime; //for Status in SourceManager
	private DB _db = null;
	
	public TCPListener(int port, int serverTimeOut, int tcpTimeOut, int msgMSS, long maxIdleTime, 
			DB db, PictureManager pictureManager, int picMSS){ 
		_stop = false;
		_port = port;
		_ServerTimeOut = serverTimeOut;
		_tcpTimeOut = tcpTimeOut;
		_msgMSS = msgMSS;
		_picMSS = picMSS;
		_maxIdleTime = maxIdleTime;
		_db = db;
		_pictureManager = pictureManager;
	}
	@Override
	public void run() {
		ServerSocket server = null;
		try
		{
			server = new ServerSocket(_port);
			server.setSoTimeout(_ServerTimeOut);
		} catch (IOException ex){
			Proj350.logger.logError("Error opening tcp listener on port: " + _port);
			Proj350.logger.close();
			System.exit(-1);
		}	
		while (!isStop()){
			Socket socket = null;
			try{
				socket = server.accept();
			} catch (IOException ex){ socket = null; }
			if (socket != null){
				String ownerIP = _db.getRecord(_db.get_OwnerName()).get_ip();
				
				if (ownerIP == null)
					ownerIP = "unknown";
				
				TCPAdapter adapter = new TCPAdapter(_db.get_OwnerName(), ownerIP, socket, _tcpTimeOut, _msgMSS);
				try{ adapter.initialize(); }
				catch (IOException ex){ 
					Proj350.logger.logError("Cannot create TCP socket in port: " + socket.getPort());
					continue;
				} 
				
				new Thread(new Handler(adapter, _db, _pictureManager, _maxIdleTime, _picMSS), "TCPSession").start();
			}
		}
		try{server.close();
		} catch (IOException e) {}

	}
	public synchronized void stop(){ _stop = true; }
	private synchronized boolean isStop(){
		return _stop;
	}

}
